package com.bw.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.bw.service.FileService;
import com.bw.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: Wrj
 * @Date: 2025/3/10 19:28
 * @Description:
 **/
@Controller
@RequestMapping("file")
public class FileController {

    @Autowired
    FileService fileService;

    @ResponseBody
    @RequestMapping("uploadeimages")
    public R images(MultipartFile file, HttpServletRequest request) throws IOException {

        if (file == null || file.isEmpty()) {
            return R.ERROR(500, "请选择文件");
        }
        //获取指定目录路径
        String realPath = request.getServletContext().getRealPath("/images");

        //创建文件上传的目标文件目录
        File dir = new File(realPath);
        //如果不存在则创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //获取原始文件名 如上传的a.jpg
        String originalFilename = file.getOriginalFilename();
        //统一上传的文件命名格式 日期+四位随机数+.文件后缀名
        String filename = DateUtil.today() + RandomUtil.randomNumbers(4) + originalFilename.substring(originalFilename.lastIndexOf("."));

        //创建目标文件
        File file1 = new File(realPath, filename);
        //上传的文件写入到目标文件
        file.transferTo(file1);
        //返回文件名
        return R.OK("/images/" + filename);
    }
}
